/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * BusquedaCliente.java
 *
 * Created on 28/07/2011, 12:35:13 AM
 */
package co.srm.vistas.funcionales;

import co.srm.entidades.Cliente;
import co.srm.manejadores.ManejadorCliente;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.RowFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import org.jdesktop.swingx.decorator.Filter;
import org.jdesktop.swingx.decorator.PatternFilter;
import org.jdesktop.swingx.decorator.FilterPipeline;

/**
 *
 * @author TilZon
 */
public class BusquedaCliente extends javax.swing.JDialog {

    private List<Cliente> clienteMemoria = null;

    /** Creates new form BusquedaCliente */
    public BusquedaCliente(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        setLocationRelativeTo(null);
        Inicializar();

    }

    public void Inicializar() {
        llenarComboConLosFiltros();
        llenarTablaClientes();
//        enviarCliente("", "", "", "", "");
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jXPanel3 = new org.jdesktop.swingx.JXPanel();
        jLabel13 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        filtroTexto = new javax.swing.JTextField();
        comboFiltros = new javax.swing.JComboBox();
        jSeparator1 = new javax.swing.JSeparator();
        jButton1 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tablaClientes = new org.jdesktop.swingx.JXTable();

        jXPanel3.setBackground(new java.awt.Color(255, 223, 98));
        jXPanel3.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(255, 255, 255), 1, true));

        jLabel13.setFont(new java.awt.Font("Arial", 3, 18));
        jLabel13.setText("Busqueda Cliente");

        javax.swing.GroupLayout jXPanel3Layout = new javax.swing.GroupLayout(jXPanel3);
        jXPanel3.setLayout(jXPanel3Layout);
        jXPanel3Layout.setHorizontalGroup(
            jXPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jXPanel3Layout.createSequentialGroup()
                .addContainerGap(310, Short.MAX_VALUE)
                .addComponent(jLabel13)
                .addGap(308, 308, 308))
        );
        jXPanel3Layout.setVerticalGroup(
            jXPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jXPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel13)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12));
        jLabel1.setText("Buscar por:");

        filtroTexto.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                filtroTextoKeyReleased(evt);
            }
        });

        jButton1.setText("Buscar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        tablaClientes.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "id","Cedula", "Nombre","Dieccion","Telefono"
            }
        ));
        tablaClientes.setEditable(false);
        tablaClientes.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tablaClientesMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tablaClientes);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jXPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(comboFiltros, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(36, 36, 36)
                .addComponent(filtroTexto, javax.swing.GroupLayout.PREFERRED_SIZE, 169, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(39, 39, 39)
                .addComponent(jButton1)
                .addContainerGap(219, Short.MAX_VALUE))
            .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 772, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 752, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jXPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(filtroTexto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(comboFiltros, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 275, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton1ActionPerformed

    private void filtroTextoKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_filtroTextoKeyReleased
        // TODO add your handling code here:
        hacerLosFiltros();
    }//GEN-LAST:event_filtroTextoKeyReleased

    private void tablaClientesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablaClientesMouseClicked
        if (evt.getClickCount() == 1) {
//            enviarCliente("", "", "", "", "");//limpiamos los datos del cliiente en la ventana prestamo
            // trae el punto donde di clik en la fila, me trae la celda
            int fila = tablaClientes.rowAtPoint(evt.getPoint());
            // en que columna estoy, los dos me traen en que celda estoy
            int columna = tablaClientes.columnAtPoint(evt.getPoint());
            if ((fila > -1) && (columna > -1)) {
                columna = 0;
                String id = tablaClientes.getValueAt(fila, columna).toString();

                Cliente cli = null;
                try {
                    cli = buscarCliente(id);
//                    System.out.println("cli = " + cli);
                } catch (Exception ex) {
                    Logger.getLogger(BusquedaCliente.class.getName()).log(Level.SEVERE, null, ex);
                    ex.printStackTrace();
                }
                if(VentanaPrestamo.origenVentanaPrestamo ==1){
//                  System.out.println("origenVentanaPrestamo2 = " + VentanaPrestamo.origenVentanaPrestamo);
                    VentanaPrestamo.clienteSt = cli;
                    enviarCliente(String.valueOf(cli.getId()), String.valueOf(cli.getIdentificacion()), cli.getNombres() + " " + cli.getApellidos(), cli.getTelefono() + "/" + cli.getCelular(), cli.getDireccion());
                    this.setVisible(false);
                    VentanaPrestamo.origenVentanaPrestamo = 0;
//               System.out.println("origenVentanaPrestamo3 = " + VentanaPrestamo.origenVentanaPrestamo);
                }
                if(VentanaPersona.origenVentanaPersona==1){
//                 System.out.println("origenVentanaPersona2 = " + VentanaPersona.origenVentanaPersona);
                    VentanaPersona.clientestP=cli;
    enviarClienteP(String.valueOf(cli.getId()),String.valueOf( cli.getIdentificacion()),cli.getNombres(),cli.getApellidos(), cli.getTelefono(),cli.getCelular(),cli.getDireccion(), cli.getObservacion());
                   this.setVisible(false);
                   VentanaPersona.origenVentanaPersona=0;
//                 System.out.println("origenVentanaPersona3 = " + VentanaPersona.origenVentanaPersona);
                  VentanaPersona.guardarPersona.setEnabled(false);
                  VentanaPersona.botonModificar.setEnabled(true);
                }

            } else {

                JOptionPane.showMessageDialog(null, "Por favor seleccione un cliente");
            }

        }
    }//GEN-LAST:event_tablaClientesMouseClicked

//////////////    System.out.println (VentanaPago.ventanaActiva);
    //. KeyboardFocusManager.getCurrentKeyboardFocusManage r () GetActiveWindow ();
//       if(VentanaPago.activo == 1){
//        }
    public void enviarCliente(String id, String cedula, String nombre, String telefonos, String direccion) {
        VentanaPrestamo.campoIdCliente.setText(String.valueOf(id));
        VentanaPrestamo.campoCedula.setText(cedula);
        VentanaPrestamo.campoNombre.setText(nombre);
        VentanaPrestamo.campoTelefono.setText(telefonos);
        VentanaPrestamo.areaDireccion.setText(direccion);
    }

       public void enviarClienteP( String id, String cedula, String nombre,String apellido, String telefonos, String celular, String direccion, String observacion) {
       VentanaPersona.campoIdCliente.setText(String.valueOf(id));
        VentanaPersona.campoIdentificacion.setText(cedula);
        VentanaPersona.campoNombre.setText(nombre);
        VentanaPersona.campoApellido.setText(apellido);
        VentanaPersona.campoTelefono.setText(telefonos);
        VentanaPersona.campoCelular.setText(celular);
        VentanaPersona.areaDireccion.setText(direccion);
        VentanaPersona.areaObservacion.setText(observacion);
    }

    public void llenarTablaClientes() {
        ManejadorCliente mCliente = new ManejadorCliente();
        List<Cliente> clientes = mCliente.consultarAllUsuarios();
        this.clienteMemoria = clientes;
        DefaultTableModel dtm = (DefaultTableModel) tablaClientes.getModel();
        //"id","Cedula", "Nombre","Dieccion","Telefono"
        for (Cliente cliente : clientes) {
            Object[] fila = {cliente.getId(), cliente.getIdentificacion(), cliente.getNombres() + " " + cliente.getApellidos(), cliente.getDireccion(), cliente.getTelefono() + " - " + cliente.getCelular()};
            dtm.addRow(fila);
        }
    }

    public void llenarTablaClientesEnMemoria() {
        ManejadorCliente mCliente = new ManejadorCliente();
        List<Cliente> clientesMe = this.clienteMemoria;
        DefaultTableModel dtm = (DefaultTableModel) tablaClientes.getModel();
        if (clientesMe != null) {
            for (Cliente cliente : clientesMe) {
                Object[] fila = {cliente.getId(), cliente.getIdentificacion(), cliente.getNombres() + " " + cliente.getApellidos(), cliente.getDireccion(), cliente.getTelefono() + " - " + cliente.getCelular()};
                dtm.addRow(fila);
            }
        }
    }

    public void llenarComboConLosFiltros() {

        List<TableColumn> columnas = tablaClientes.getColumns();
        comboFiltros.addItem("..Sin filtro...");
        for (TableColumn tableColumn : columnas) {
            String col = tableColumn.getHeaderValue().toString().trim();
            if (tableColumn.getModelIndex() != 0) {
                comboFiltros.addItem(col);
            }
        }
        //ocultando columna id star
        tablaClientes.getColumnModel().getColumn(0).setMaxWidth(0);
        tablaClientes.getColumnModel().getColumn(0).setMinWidth(0);
        tablaClientes.getTableHeader().getColumnModel().getColumn(0).setMaxWidth(0);
        tablaClientes.getTableHeader().getColumnModel().getColumn(0).setMinWidth(0);
        //ocultando columna id end

        tablaClientes.getColumnModel().getColumn(1).setMaxWidth(95);
        tablaClientes.getColumnModel().getColumn(1).setMinWidth(95);

        tablaClientes.getColumnModel().getColumn(4).setMaxWidth(195);
        tablaClientes.getColumnModel().getColumn(4).setMinWidth(195);
    }

    private void hacerLosFiltros() {
        try {
            limpiarTabla();
            String filtro = filtroTexto.getText();
            int columna = comboFiltros.getSelectedIndex();
            if (columna > 0 && !filtro.isEmpty() && filtro != null) {
                //errorLabel.setVisible(false);
                //columna-=1;
                //FilterPipeline filtros = new FilterPipeline(new Filter[] { new PatternFilter(filtro, 0, 0),new PatternFilter(filtro,1, 1) });
                PatternFilter p1 = new PatternFilter(filtro, -1, columna);
                Filter[] filterArray = {p1};
                FilterPipeline filters = new FilterPipeline(filterArray);
//                RowFilter filter = RowFilter.regexFilter(filtro);
                tablaClientes.setFilters(filters);
//                tablaClientes.setRowFilter(filter);

            } else {
                Filter[] filterArray = {};
                FilterPipeline filters = new FilterPipeline(filterArray);
                tablaClientes.setFilters(filters);
//                 tablaClientes.setRowFilter(null);
                if (columna == 0) //errorLabel.setVisible(true);
                {
                    if (filtro == null || filtro.isEmpty()) // errorLabel.setVisible(false);
                    {
//                        System.out.println("Selecione un... filtro= ");
                    }
                }
            }

            //llenarTablaClientes();
            llenarTablaClientesEnMemoria();


        } catch (Exception ex) {
            Logger.getLogger(BusquedaCliente.class.getName()).log(Level.SEVERE, null, ex);
            ex.printStackTrace();
        }
    }

    public void limpiarTabla() {
        DefaultTableModel dtm = (DefaultTableModel) tablaClientes.getModel();
        dtm.setRowCount(0);
    }

    public Cliente buscarCliente(String id) {
        Long idCliente = null;
        Cliente c = null;
        try {
            idCliente = Long.parseLong(id);
        } catch (Exception e) {
            return null;
        }
        for (Cliente cliente : clienteMemoria) {
            if (cliente.getId().equals(idCliente)) {
                c = cliente;
                break;
            }
        }

        return c;
    }
    /**
     * @param args the command line arguments
     */
//    public static void main(String args[]) {
//        java.awt.EventQueue.invokeLater(new Runnable() {
//
//            public void run() {
//                new BusquedaCliente().setVisible(true);
//            }
//        });
//    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox comboFiltros;
    private javax.swing.JTextField filtroTexto;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private org.jdesktop.swingx.JXPanel jXPanel3;
    private org.jdesktop.swingx.JXTable tablaClientes;
    // End of variables declaration//GEN-END:variables
}
